
import { goLogin, formatTime, getTimeStm } from '../../utils/util.js'
import { getStructure, getView, getMaintainList, addMaintain, updateMaintain, delMaintain } from '../../api/getData.js';
const globalData = getApp().globalData;
const app = getApp();
let template = require('../../pages/tabBar/tab-bar.js');

Page({
  data: {
    userName: '',
    treeRes: {},
    showNav: false,
    deatilNav: [],
    deatilList: [],
    devices: false,
    mostStatus: '',
    show: false,
    showPicker: false,
    treeID: '',
    eventList: [],
    startTime:'',
    endTime:'',
    inputValue:'',
    isShow: false,
    descriList: ['日保', '月保', '项修', '轮保','自定义'],
    choosedIndex: 0, // 被选中的描述
    total: 0,
    page: 1,
    descrInputValue:'',
    scrollHeight: '100%',
    px2rpx: 2,
    scrollTop: 0,
    treeInfo: ''
  },
  onLoad: function (options) {
    template.tabbar("tabBar", 1, this);
    this.getSystem();
    this.setData({
      userName: wx.getStorageSync('username')
    })
    app.watch('deatilNav', (value) => {
      this.data.deatilNav = [];
      const newSet = new Set(value);
      this.setData({
        deatilNav: Array.from(newSet),
      })
    })
    app.watch('deatilList', (value) => {
      this.data.deatilList = [];
      this.setData({
        deatilList: value,
      })
    })
    app.watch('showNav', (value) => {
      this.setData({
        showNav: value,
      })
    })
    app.watch('mostStatus', (value) => {
      this.setData({
        mostStatus: value,
      })
    });
    app.watch('treeInfo', (value) => {
      console.log('value', value)
      this.setData({
        eventList: [],
        page: 1
      })
      this.getMaintainListData(value.treeID, 1);
    }) 
  },

  getSystem: function () {
    var self = this;
    wx.getSystemInfo({
      success: function (res) {
        self.setData({
          scrollHeight: res.windowHeight,
          px2rpx: 750 / res.windowWidth
        })
      },
    });
  },

  onShow() {
    this.setData({
      eventList: [],
      page: 1
    })
    if (wx.getStorageSync('canRequest')) {
      this.getStructureData();
    } else {
      let { multiList, deviceName } = app.globalData;
      let { devices, sceneID } = this.data;
      let treeName = [];
      multiList.forEach(item => {
        treeName.push(item.name)
      })
      multiList[multiList.length - 1].scene && (sceneID = multiList[multiList.length - 1].scene)
      this.setData({
        // deatilNav: treeName,
        treeName: treeName.join(','),
      })
      this.getViewData()
    }
    wx.setStorageSync('canRequest', true)
  },
  // 获取场景树
  getStructureData() {
    getStructure().then(res => {
      if (res.status == '0' || res.resCode !== 'SUCCESS') {
        goLogin()
        return
      }
      let result = res.result[0];
      app.globalData.result = res.result;
      this.setData({
        treeRes: result,
        deatilNav: app.globalData.deatilNav,
      });
      this.getViewData(result.children[0].children && result.children[0].children.length ? result.children[0].children[0] : result.children[0])
    })
  },

  // 获取总览信息
  getViewData(params) {
    let { devices, treeID, sceneID } = params;
    console.log('treeInfo', treeID)
    this.setData({
      treeID: wx.getStorageSync('treeInfo').treeID !== undefined ? wx.getStorageSync('treeInfo').treeID : params.treeID
    });
    this.getMaintainListData(wx.getStorageSync('treeInfo').treeID !== undefined ? wx.getStorageSync('treeInfo').treeID : params.treeID,1);
    getView(wx.getStorageSync('treeInfo').treeID !== undefined ? wx.getStorageSync('treeInfo').treeID : params.treeID, sceneID, devices = true).then(res => {
      this.formatGetView(res)
    })
  },

  // 处理总览数据 
  formatGetView(res) {
    if (res.resCode == 'SUCCESS') {
      app.globalData.deatilList = res.result.view
    }
  },
  // 页面上拉加载更多
  loadMoreList() {
    let eventLength = this.data.eventList.length;
    console.log(eventLength)
    if (eventLength) {
      if (eventLength >= this.data.total) {
        wx.showToast({
          title: '已经到底了',
          icon: 'none'
        })
        return
      }
      this.setData({
        page: ++this.data.page
      })
      // 这里不知道为什么用this.data.handleState这个属性，应该是treeID值
      // this.getMaintainListData(this.data.handleState, this.data.page);
      this.getMaintainListData(this.data.treeID, this.data.page);
    }
  },

// 获取维保列表
  getMaintainListData(params,page) {
    this.setData({
      treeID: params
    })
    wx.showLoading({
      title: '加载中',
    })
    getMaintainList(params, page).then(res => {
      if (res.resCode == 'SUCCESS') {
        wx.hideLoading();
        let newEventList = res.result.eventList
        this.setData({
          eventList: this.data.eventList.concat(...newEventList),
          total: res.result.count,
          scrollHeight: 515 * this.data.px2rpx
        });
      }    
    })
  },
  
  // 阻止蒙版层滚动
  preventTouchMove(e) {
    return false
  },
  // 隐藏导航
  closeNav() {
    this.setData({
      showNav: false
    })
  },

  // 显示导航
  showNavFn() {
    this.setData({
      showNav: true
    })
  },

  // 弹窗
  addModal() {
    let timeStr = new Date(new Date().toLocaleDateString());
    this.setData({
      show: true,
      startTime: formatTime(timeStr, 1),
      endTime: formatTime(new Date(), 1),
      choosedIndex: 0
    })
  },

  // 是否展示描述下拉框
  showDialogfn() {
    this.setData({
      isShow: this.data.isShow === false ? true : false
    })
  },
  //取消picker
  cancelPicker() {
    this.showDialogfn()
  },

  // 选择描述
  chooseDescribe(e) {
    this.setData({
      choosedIndex: e.detail.value[0],
    })
  },

  // 确定选择
  pickerSure() {
    this.setData({
      inputValue: this.data.descriList[this.data.choosedIndex],
      descrInputValue: ''
    })
    this.showDialogfn()
  },

  handleSelecteDate(e) {
    let { date, timeSign } = e.detail,
      timeArr = [getTimeStm(this.data.startTime), getTimeStm(this.data.endTime)],
      dataStm = new Date().getTime();

    timeArr[timeSign] = getTimeStm(date);
    if (timeArr[timeSign] > dataStm) {
      wx.showToast({
        title: '时间不能大于当前时间',
        icon: 'none'
      })
      return
    }
    if (timeArr[0] === timeArr[1]) {
      wx.showToast({
        title: '时间不能相等',
        icon: 'none'
      })
      return
    }

    if (timeArr[0] > timeArr[1]) {
      wx.showToast({
        title: '开始时间不能大于结束时间',
        icon: 'none'
      })
      return
    }

    if (timeArr[1] - timeArr[0] > 15724800000) {
      wx.showToast({
        title: '时间不能大于半年',
        icon: 'none'
      })
      return
    }

    let obj = {};
    obj[timeSign == 0 && "startTime" || "endTime"] = date;
    this.setData(obj)
    this.hiddencover()
  },
  pickerShow: function (e) {
    let sign = e.currentTarget.dataset.sign;
    this.setData({
      showPicker: true,
      timeSign: sign
    });
    this.selectComponent('.date-picker').formMatInit(sign == 0 && this.data.startTime || this.data.endTime)

  },
  hiddencover() {
    this.setData({
      showPicker: false
    })
  },
  // 自定义描述
  bindKeyInput (e) {
    this.setData({
      descrInputValue: e.detail.value
    })
  },
  // 点击确定
  sure() {
    this.setData({
      treeID: wx.getStorageSync('treeInfo').treeID !== undefined ? wx.getStorageSync('treeInfo').treeID : this.data.treeID,
      page: 1
    })
    let { startTime, endTime, inputValue, treeID, choosedIndex, descrInputValue, descriList  } = this.data;
    let tmsStart = new Date(startTime.split('-').join('/')).getTime(),
      tmsEnd = new Date(endTime.split('-').join('/')).getTime(),
      nowTms = new Date().getTime();
    if (tmsStart > nowTms || tmsEnd > nowTms) {
      wx.showToast({
        title: '时间不能大于当前时间',
        icon: 'none'
      })
      return
    }
    if (choosedIndex === 4 && !descrInputValue) {
      wx.showToast({
        title: '请输入描述',
        icon: 'none'
      })
      return
    }
    let comment = this.data.descrInputValue
    if (choosedIndex !== 4) {
      this.data.descrInputValue = ''
      comment = this.data.descriList[choosedIndex]
    }
    console.log(wx.getStorageSync('treeInfo').treeID ? wx.getStorageSync('treeInfo').treeID : treeID)
    addMaintain(tmsStart, tmsEnd, comment, wx.getStorageSync('treeInfo').treeID !== undefined ? wx.getStorageSync('treeInfo').treeID : treeID)
      .then(res => {
        if (res.resCode === "SUCCESS") {
          wx.showToast({
            title: '添加成功！',
            icon: 'none'
          })
          this.setData({
            eventList: [],
            page: 1
          })
          this.getMaintainListData(this.data.treeID,this.data.page);
          this.setData({
            show: false
          })
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      })
  },
  //点击取消
  hide() {
    this.setData({
      show: false
    })
  },

  // 编辑更新
  update(e) {
    let item = e.currentTarget.dataset.item;
    let value = e.detail.value;
    let startTimeStr = new Date(item.startDate.replace(/\-/g,'\/')).getTime();
    let endTimeStr = new Date(item.endDate.replace(/\-/g,'\/')).getTime();
    if (item.comment === value) return
    wx.showLoading({
      title: '加载中'
    })
    updateMaintain(startTimeStr, endTimeStr, value, item.treeID, item.eventID)
      .then(res => {
        if (res.resCode === "SUCCESS") {
          wx.hideLoading()
          this.setData({
            eventList: [],
            page: 1
          })
          this.getMaintainListData(this.data.treeID, this.data.page);
          setTimeout(() => {
            this.setData({
              show: false
            })
          }, 800)
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      })
  },
  // 删除
  delItem(e) {
    if(!this.data.treeID){
      this.setData({
        treeID: wx.getStorageSync('treeInfo').treeID !== undefined ? wx.getStorageSync('treeInfo').treeID : ''
      })
    }
   
    wx.showModal({
      title: '提示',
      content: '确定要删除本条事件吗？',
      success: (res) => {
        if (res.confirm) {
          delMaintain(e.currentTarget.dataset.id).then(res => {
            console.log(res)
            if (res.resCode === "SUCCESS") {
              wx.showToast({
                title: "删除成功!",
                icon: 'none'
              });
              this.setData({
                eventList: [],
                page: 1
              })
              this.getMaintainListData(this.data.treeID,this.data.page);
            } else {
              wx.showToast({
                title: "删除失败!",
                icon: 'none'
              })
            }
          })
        } else {
          // 取消删除
        }
      }
    })
  }
})